package com.tc.workflow;

import com.tc.workflow.enums.ErrorCodePlus;
import com.xiaoleilu.hutool.lang.Dict;
import org.team4u.dao.core.Dao;
import org.team4u.kit.core.util.AssertUtil;
import org.team4u.sql.builder.Sql;
import org.team4u.sql.builder.builder.ParameterizedSqlBuilder;
import org.team4u.sql.builder.content.FileSqlContentManager;
import org.team4u.sql.builder.content.SqlContents;
import org.team4u.sql.builder.content.template.JetbrickSqlTemplate;
import org.team4u.sql.builder.util.SqlBuilders;

import java.util.Map;

/**
 * @author Jay Wu
 */
public class DaoService {

    private Map<String, Dao> daoMap;

    public DaoService(Map<String, Dao> daoMap, String[] sqlPaths) {
        this.daoMap = daoMap;
        SqlContents.getInstance().setSqlTemplate(new JetbrickSqlTemplate());
        SqlContents.getInstance().register(new FileSqlContentManager(sqlPaths).watch(5));
    }

    public <T> T execute(Dict request, SqlCallback<T> callback) {
        AssertUtil.isNotEmpty(ErrorCodePlus.PARAM_ERROR, request, "request");

        String sqlDs = request.getStr("sqlDs");
        String sqlKey = request.getStr("sqlKey");

        AssertUtil.isNotEmpty(ErrorCodePlus.PARAM_ERROR, sqlDs, "sqlDs");
        AssertUtil.isNotEmpty(ErrorCodePlus.PARAM_ERROR, sqlKey, "sqlKey");

        Dao dao = getDao(sqlDs);
        AssertUtil.isNotEmpty(ErrorCodePlus.PARAM_ERROR, dao, "dao");

        ParameterizedSqlBuilder sqlBuilder = SqlBuilders.sqlKey(sqlKey);
        for (Map.Entry<String, Object> entry : request.entrySet()) {
            sqlBuilder.setParameter(entry.getKey(), entry.getValue());
        }

        Sql sql = sqlBuilder.create();
        AssertUtil.isNotEmpty(ErrorCodePlus.PARAM_ERROR, sql, "sql");
        AssertUtil.isNotEmpty(ErrorCodePlus.PARAM_ERROR, sql.getContent(), "sqlContent");

        return callback.handle(dao, sql);
    }

    public Dao getDao(String key) {
        return daoMap.get(key);
    }

    public interface SqlCallback<T> {

        T handle(Dao dao, Sql sql);
    }
}